package com.winhxd.b2c.admin.utils;

import com.qcloud.Module.Vod;
import com.qcloud.QcloudApiModuleCenter;
import com.qcloud.Utilities.Json.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.meta.InsertOnly;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import it.sauronsoftware.jave.MultimediaInfo;
import it.sauronsoftware.jave.Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.TreeMap;

public class VodUpload {

	private static final Logger log = LoggerFactory.getLogger(VodUpload.class);
	private static TreeMap<String, Object> config = new TreeMap<String, Object>();

	static {
		config.put("SecretId", "AKIDkVVNeyt1NVavQYafXbQMnhoYVFcWLthi");
		config.put("SecretKey", "l1ZUmey82VzvMU5PJHECW6Cqi21PNhWC");
		config.put("RequestMethod", "POST");
		config.put("DefaultRegion", "gz");
	}

	/**
	 * @Author zhengwei
	 * @Date 2017/8/3 16:57
	 * @Description
	 * @Return
	 * @Param fileName 视频名称
	 * @Param fileType 视频类型
	 * @Param destFile 视频地址
	 **/
	public static String upload(String fileName,String fileType,String destFile) {
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(), config);
		String fileId = null;  //腾讯fileId
		try{
			log.info("starting...");
			long fileSize = new File(destFile).length();
			int code;
			if(fileSize<=0){
				log.info("wrong file path...");
			}
			TreeMap<String, Object> params = new TreeMap<>();
				/*
				 * 亲，输入参数的类型，记得参考wiki详细说明
				 */
			params.put("videoType", fileType); //视频类型
			params.put("videoName", fileName); //视频名称
			params.put("videoSize", fileSize); //视频文件的大小(单位：字节)
			/* 后续可能扩展用
				params.put("coverType", fileSize); //封面文件类型
				params.put("coverName", fileSize); //封面文件名称
				params.put("coverSize", fileSize); //封面文件的大小(单位：字节)
				params.put("procedure", fileSize); //视频后续任务操作
			*/

			String result = module.call("ApplyUpload", params);
			log.info(result);
			JSONObject json_result = new JSONObject(result);
			code = json_result.getInt("code");
			if (code == 0) { //上传成功
				//获取VOD确认上传时使用的会话 Key
				String vodSessionKey = json_result.getString("vodSessionKey");
				String bucket = json_result.getString("storageBucket");
				String region = json_result.getString("storageRegion");
				String videoDst = json_result.getJSONObject("video").getString("storagePath");

				// 第二步，上传文件到COS
				long appId = 10022853;//第二步COS要使用公共的bucket：10022853，不要使用您自己的bucket。2017-08-07
				ClientConfig clientConfig = new ClientConfig();
				clientConfig.setRegion(region);
				clientConfig.setSignExpired(24 * 3600);
				Credentials cred = new Credentials(appId, config.get("SecretId").toString(), config.get("SecretKey").toString());
				COSClient cosClient = new COSClient(clientConfig, cred);

				UploadFileRequest uploadFileRequest = new UploadFileRequest(bucket, videoDst, destFile);
				uploadFileRequest.setInsertOnly(InsertOnly.OVER_WRITE);
				String uploadFileRet = cosClient.uploadFile(uploadFileRequest);
				System.out.print("upload video to cos|recv:");
				System.out.println(uploadFileRet);

				log.info("vodSessionKey" + vodSessionKey);
				//第三步，确认上传
				fileId = getFileIdByKey(vodSessionKey);
			} else {
				log.error("腾讯云视频上传error:(" + code + ")" + json_result.getString("message"));
			}
		}
		catch (Exception e) {
			log.info("",e);
		}
		return fileId;
	}

	/**
	 * @Author zhengwei
	 * @Date 2017/8/3 16:52
	 * @Description 腾讯云确认上传
	 * @Return string
	 * @Param vodSessionKey
	 **/
	private static String getFileIdByKey(String vodSessionKey) {
		String fileId = null;
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(), config);
		TreeMap<String, Object> params = new TreeMap<>();
		params.put("vodSessionKey", vodSessionKey);
		try {
			String result = module.call("CommitUpload", params);
			log.info(result);
			JSONObject json_result = new JSONObject(result);
			int code = json_result.getInt("code");
			if (code == 0) { //确认成功
				fileId = json_result.getString("fileId");
			} else {
				log.error("腾讯云视频上传error:(" + code + ")" + json_result.getString("message"));
			}
		} catch (Exception e) {
			log.info("",e);
		}
		return fileId;
	}

	/**
	 * 转码
	 * @param fieldId
	 * @return
	 */
	public static int videoConvertVodFile(String fieldId){
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(), config);
		TreeMap<String, Object> params = new TreeMap<>();
		params.put("fileId", fieldId);
		try {
			String result = module.call("ConvertVodFile", params);
			log.info(result);
			JSONObject json_result = new JSONObject(result);
			return json_result.getInt("code");
		} catch (Exception e) {
			log.info("",e);
		}
		return -1;
	}

	/**
	 * 根据视频信息列表，获取时长
	 * @param fieldId
	 * @return
	 */
	public static int videoDescribeVodInfo(String fieldId,String destFolder){
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(), config);
		TreeMap<String, Object> params = new TreeMap<>();
		params.put("fileId", fieldId);
		try {
			//DescribeVodPlayUrls    DescribeVodInfo
			String result = module.call("GetVideoInfo", params);
			log.info(result);
			JSONObject json_result = new JSONObject(result);
			JSONObject basicInfo = json_result.getJSONObject("basicInfo");
			int duration= basicInfo.getInt("duration");
			if(duration==0){
				//本地获取时长
				File source = new File(destFolder);
				log.info("VodUpload文件路径"+destFolder);
				Encoder encoder = new Encoder();
				File[] file = source.listFiles();
				int sum = 0;
				for (File file2 : file) {
					try {
						MultimediaInfo m = encoder.getInfo(file2);
						long ls = m.getDuration() / 1000;//ls是获取到的秒数
						sum += ls;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				duration=sum;
			}
			return duration;
		} catch (Exception e) {
			log.info("",e);
		}
		return 0;
	}

	public static JSONObject getVideoInfo(String fieldId){
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(), config);
		TreeMap<String, Object> params = new TreeMap<>();
		params.put("fileId", fieldId);
		//此处是获取基本信息，如果需要更多信息，参数还有很多，参考https://cloud.tencent.com/document/product/266/8586#basicinfo.EF.BC.88.E8.A7.86.E9.A2.91.E5.9F.BA.E7.A1.80.E4.BF.A1.E6.81.AF.EF.BC.89
		params.put("infoFilter.0", "basicInfo");
		JSONObject json_result = null;
		try {
			String result = module.call("GetVideoInfo", params);
			log.info(result);
			json_result = new JSONObject(result);
			return json_result;
		} catch (Exception e) {
			log.info("",e);
		}
		return null;
	}

	/**
	 * 获取播放地址信息
	 * @param fieldId
	 * @return
	 */
	public static String videoDescribeVodPlayUrls(String fieldId){
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(), config);
		TreeMap<String, Object> params = new TreeMap<>();
		params.put("fileId", fieldId);
		try {
			String result = module.call("GetVideoInfo", params);
			log.info(result);
			JSONObject json_result = new JSONObject(result);
			JSONObject basicInfo = json_result.getJSONObject("basicInfo");
			return basicInfo.getString("sourceVideoUrl");
		} catch (Exception e) {
			log.info("",e);
		}
		return null;
	}

	/**
	 * 删除视频
	 * @param fieldId
	 */
	public static void videoDeleteVodFile(String fieldId){
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(), config);
		TreeMap<String, Object> params = new TreeMap<>();
		params.put("fileId", fieldId);
		params.put("priority", 0);
		try {
			String result = module.call("DeleteVodFile", params);
			log.info(result);
		} catch (Exception e) {
			log.info("",e);
		}
	}
	/**
	 * 视频截图
	 * @param fieldId
	 */
	public static void Snapshot(String fieldId){
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(), config);
		TreeMap<String, Object> params = new TreeMap<>();
//		params.put("Action", "DescribeMediaInfos");
		params.put("FileIds.0", "5285890784378860623");
		params.put("Version", "2018-07-17");
		try {
			String result = module.call("DescribeMediaInfos", params);
			log.info(result);
		} catch (Exception e) {
			log.info("",e);
		}
	}

	public static void main(String[] args) {

		Snapshot("5285890783768647465");
//
//		String fileId = upload("3333", "mp4", "C:/Users/yuluyuan/Desktop/d46b18e81da2fbe8f3ebb3dd38e503e4.mp4");
//		System.out.println(fileId);
//		//转码
//		int count = videoConvertVodFile(fileId);
//		if (count == 0) { //转码成功
//			//获取时长
//			int doa = videoDescribeVodInfo(fileId,"D:/opt/retail/img/picinfo/01b9c0f7f5c94adbae0b1439e3f36fb8/");
//			String url=videoDescribeVodPlayUrls(fileId);
//			System.out.println(doa);
//			System.out.println(url);
//
//
//		}
	}
}
